<?php
require 'PHPExcel/PHPExcel.php';
class excel_widget
{
    private $_HANDLE;
    private $_DATA = array();
    private $_FILE;
    private $_EXPORT_DIR = '';
    private $_EXPORT = false;
    private $subfix = '.xls';
    private $excel_format = 'Excel2007';

    public function __construct() {
        $this->_HANDLE = new PHPExcel();
        $this->_HANDLE->getDefaultStyle()->getFont()->setName('宋体');
        $this->_EXPORT_DIR = EXPORT_PATH;
    }
    private function set_data() {
        foreach ($this->_DATA as $sheet_id => $sheet_data) {
            if (is_array($sheet_data)) {
                $this->_HANDLE->createSheet($sheet_id);
                $_sheet = $this->_HANDLE->getSheet($sheet_id);

                $sheet_name = isset($sheet_data['name']) ? : 'sheet_'.$sheet_id;
                $_sheet->setTitle($sheet_name);

                if (is_array($sheet_data['data']) && $table = $sheet_data['data']) {
                    $row_index = 0;
                    //一级标题
                    if (isset($table['title']) && is_array($table['title'])) {
                        foreach ($table['title'] as $k => $v) {
                            $column_title_name = tools_helper::excel_column_encode($k);
                            if ($k === 0) {
                                $_sheet->getColumnDimension($column_title_name)->setWidth(10);
                            } else {
                                $_sheet->getColumnDimension($column_title_name)->setWidth(15);
                            }
                            $_sheet->setCellValue($column_title_name.'1', $v);
                            $_sheet->getStyle($column_title_name)->getAlignment()->setWrapText(true);
                        }
                        $row_index = 1;
                    }

                    //二级标题
                    if (isset($table['column']) && is_array($table['column'])) {
                         foreach ($table['column'] as $k => $v) {
                            $column_name = tools_helper::excel_column_encode($k);
                            if ($k === 0) {
                                $_sheet->getColumnDimension($column_name)->setWidth(10);
                            } else {
                                $_sheet->getColumnDimension($column_name)->setWidth(20);
                            }
                            $_sheet->setCellValue($column_name.'2', $v);
                            $_sheet->getStyle($column_name)->getAlignment()->setWrapText(true);
                        }
                        $row_index = 2;
                    }
                    //设置数据格式
                    $table['format'] = isset($table['format']) ? $table['format'] : [['type' => 'string']];
                    foreach ($table['format'] as $column_key => $column_config) {
                        $column_index = tools_helper::excel_column_encode($column_key);
                        switch ($column_config['type']) {
                            case 'string':
                                $_sheet->getStyle($column_index)->getNumberFormat()->setFormatCode("@");
                                break;
                        }
                    }
                    //填充数据
                    foreach ($table['data'] as $row_key => $row_data) {
                        foreach ($row_data as $column_key => $column_data) {
                            $index = tools_helper::excel_column_encode($column_key) . ($row_key + $row_index + 1);
                            $_sheet->setCellValue($index, $column_data);
                        }
                    }
                }
            }
        }
    }

    private function exec_export() {
        $file_name = $this->_FILE . $this->subfix;
        $objWriter = PHPExcel_IOFactory::createWriter($this->_HANDLE, $this->excel_format);
        if ($this->_EXPORT) {
            $objWriter->save($this->_EXPORT_DIR .'/'. $file_name);
        } else {
            //设置页面类型
            header("Content-Type: application/vnd.ms-excel");
            //用于下载的文件头
            header("Content-Type: application/force-download");
            header("Content-Type: application/download");
            header("Content-Type: application/octet-stream");

            // ff正常，ie不正常，下面是从网站找到的解决方案
            if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
                $file_name = rawurlencode($file_name);
            }
            header("Content-Disposition: attachment; filename=" . $file_name);
            header("Content-Transfer-Encoding: binary");
            //最后修改时间
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            //不使用缓存
            header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
            header('Cache-Control: public');
            header("Expires: 0");
            header("Pragma: public");
            $objWriter->save('php://output');
            exit;
        }
    }
    /**
     * [导出Excel方法]
     * @param  [string] $file_name [description]
     * @param  [array] $data      [description]
     * @param  [bool] $export    [description]
     * @return [type]            [description]
     *  数据格式:
     *  $data = [[
    *     'name' => 'Demo',
    *     'data' => [
    *         'title' => ['name', 'sex', 'age'], 一级标题
    *         'column' => ['name', 'sex', 'age'], 二级标题 可省略
    *         'format' => [['type' => 'string']], 数据格式 默认string
    *         'data' => [
    *             ['admin', '0', '20'],
    *             ['root', '1', '100']
    *         ]
    *     ]
     *]];
     */
    public function export($file_name, $data, $export = false) {
        if (empty($data) || empty($file_name)) {
            return false;
        }

        $this->_FILE = $file_name;
        $this->_EXPORT = !!$export;
        $this->_DATA = $data;

        $this->set_data();

        $this->exec_export();
    }
    public function getExcelObj()
    {
        $objPHPExcel = new PHPExcel();
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        //设置当前的sheet索引，用于后续的内容操纵
        $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $objPHPExcel->getActiveSheet();
        return array($objActSheet, $objWriter);
    }
    public function download($objWriter, $filename)
    {
        if (empty($filename)) {
            throw new Exception("文件名不存在!");
        }
        $filename = $filename . $this->subfix;
        if (! $objWriter instanceof PHPExcel_Writer_Excel5) {
            throw new Exception("Error PHPExcelWriter Object");
        }
        //设置页面类型
        header("Content-Type: application/vnd.ms-excel");
        //用于下载的文件头
        header("Content-Type: application/force-download");
        header("Content-Type: application/download");
        header("Content-Type: application/octet-stream");

        // ff正常，ie不正常，下面是从网站找到的解决方案
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
            $filename = rawurlencode($filename);
        }
        header("Content-Disposition: attachment; filename=" . $filename);
        header("Content-Transfer-Encoding: binary");
        //最后修改时间
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        //不使用缓存
        header('Cache-Control: ust-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: public');
        header("Expires: 0");
        header("Pragma: public");
        $objWriter->save('php://output');
        exit;
    }
}
?>
